package com.smart.smartdata;

import android.content.Intent;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smart.smartdata.eventbus.EventBus;
import com.smart.smartdata.eventbus.EventNames;
import com.smart.smartdata.models.UpdateDataModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.smart.smartdata.MessageListActivity.Cache_Key;

public class RecordedDataActivity extends AppCompatActivity implements EventBus.SubscriberChangeListener {
    @Bind(R.id.cl_content)
    ConstraintLayout cl_content;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_title_heart)
    TextView tvTitleHeart;
    @Bind(R.id.fl_heart_content)
    FrameLayout flHeartContent;
    @Bind(R.id.tv_title_brain)
    TextView tvTitleBrain;
    @Bind(R.id.fl_brain_content)
    FrameLayout flBrainContent;
    @Bind(R.id.tv_title_temper)
    TextView tvTitleTemper;
    @Bind(R.id.fl_temper_content)
    FrameLayout flTemperContent;
    @Bind(R.id.tv_title_o)
    TextView tvTitleO;
    @Bind(R.id.fl_o_content)
    FrameLayout flOContent;
    @Bind(R.id.tv_title_muscle)
    TextView tvTitleMuscle;
    @Bind(R.id.fl_muscle_content)
    FrameLayout flMuscleContent;


    @Bind(R.id.chart_heart)
    LineChart chart_heart;
    @Bind(R.id.chart_temper)
    LineChart chartTemper;
    @Bind(R.id.chart_brain)
    LineChart chartBrain;
    @Bind(R.id.tv_blood)
    TextView tvBlood;
    @Bind(R.id.chart_muscle)
    LineChart chartMuscle;
    @Bind(R.id.tv_start_time)
    TextView tvStartTime;
    @Bind(R.id.tv_stop_time)
    TextView tvStopTime;
    private long testTime =0;
    private boolean isStart = false;

    private long startTime = 0; // 记录开始时间

    Handler handler = new Handler();

    Runnable updateTimeRunnable = new Runnable() {
        @Override
        public void run() {

            if(!isStart){

                return;
            }
            long currentTime = System.currentTimeMillis();

            testTime = currentTime - startTime;

            messageData.testTime = testTime;

            String t = formatLongToTimeStr(testTime/1000);

            tvTime.setText("测试时长: " +t);

            handler.postDelayed(this, 1000); // 1秒后再次执行
        }
    };

    private MessageData messageData;
    private List<UpdateDataModel> models ;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorded_data);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);//透明状态栏
        ButterKnife.bind(this);


        messageData = (MessageData)getIntent().getSerializableExtra("messageData");

        tvName.setText(messageData.name);

        messageData.testTime = testTime;

        models = new ArrayList<>();

        messageData.models =models;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String currentDate = sdf.format(new Date());
        messageData.testDate = currentDate;

        cl_content.setOnClickListener(view -> {

        });


        initChart(chart_heart);

        initChartTemp(chartTemper);

        initChart3(chartBrain);
        initChart4(chartMuscle);

        chart_heart.setData(generateDataLine(100));

        //chartTemper.setData(generateDataLine2(100));

        setTempData();

        chartBrain.setData(generateDataLine3(100));
        chartMuscle.setData(generateDataLine4(100));


    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    @OnClick(R.id.tv_start_time)
    public void onViewClick() {
        isStart = true;
        startTime = System.currentTimeMillis();
        handler.post(updateTimeRunnable);
    }

    @OnClick(R.id.tv_stop_time)
    public void onViewClic() {
        isStart = false;
        handler.removeCallbacks(updateTimeRunnable);
    }


    private void initChart(LineChart chart) {
        chart.setNoDataText("暂无数据");
        chart.setDrawGridBackground(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineColor(0xffE3ECF0);
        xAxis.setTextSize(6);
        xAxis.setTextColor(0xff878F99);


        YAxis leftAxis = chart.getAxisLeft();

        leftAxis.setLabelCount(5, false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setAxisLineColor(0xff878F99);
        leftAxis.setTextColor(0xff878F99);
        leftAxis.setTextSize(6);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);


        // set data


        // do not forget to refresh the chart
        // holder.chart.invalidate();
        chart.animateX(750);

        chart.getLegend().setEnabled(false); // 隐藏底部图例
        chart.getDescription().setText("时间");
        chart.getDescription().setTextColor(0xff7c8589);
        chart.getDescription().setTextSize(8);
        chart.getDescription().setEnabled(true);

    }

    private void initChartTemp(LineChart chart) {
        chart.setNoDataText("暂无数据");
        chart.setDrawGridBackground(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineColor(0xffE3ECF0);
        xAxis.setTextSize(6);
        xAxis.setTextColor(0xff878F99);


        YAxis leftAxis = chart.getAxisLeft();

        // leftAxis.setLabelCount(5, false);
        // leftAxis.setAxisMinimum(10f); // this replaces setStartAtZero(true)
        leftAxis.setAxisLineColor(0xff878F99);
        leftAxis.setTextColor(0xff878F99);
        leftAxis.setTextSize(6);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);


        // set data


        // do not forget to refresh the chart
        // holder.chart.invalidate();
        chart.animateX(750);

        chart.getLegend().setEnabled(false); // 隐藏底部图例
        chart.getDescription().setText("时间");
        chart.getDescription().setTextColor(0xff7c8589);
        chart.getDescription().setTextSize(8);
        chart.getDescription().setEnabled(true);

    }

    private void initChart3(LineChart chart) {
        chart.setNoDataText("暂无数据");
        chart.setDrawGridBackground(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // 设置网格线的样式为虚线
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{5f, 5f}, 0f));

        // 设置是否绘制轴线
        xAxis.setDrawAxisLine(true);

        xAxis.setAxisLineColor(0xffE3ECF0);
        xAxis.setTextSize(6);

        // 设置轴线的颜色
        xAxis.setTextColor(0xff878F99);

        // 设置轴线的宽度
        xAxis.setAxisLineWidth(2f);


        YAxis leftAxis = chart.getAxisLeft();

        leftAxis.setLabelCount(5, false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setAxisLineColor(0xff878F99);
        leftAxis.setTextColor(0xff878F99);
        leftAxis.setTextSize(6);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);


        // set data


        // do not forget to refresh the chart
        // holder.chart.invalidate();
        chart.animateX(750);

        chart.getLegend().setEnabled(false); // 隐藏底部图例
        chart.getDescription().setText("时间");
        chart.getDescription().setTextColor(0xff7c8589);
        chart.getDescription().setTextSize(8);
        chart.getDescription().setEnabled(true);

    }

    private void initChart4(LineChart chart) {
        chart.setNoDataText("暂无数据");
        chart.setDrawGridBackground(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        // 设置是否绘制网格线
        xAxis.setDrawGridLines(true);

        // 设置网格线的样式为虚线
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{5f, 5f}, 0f));


        xAxis.setAxisLineColor(0xffE3ECF0);
        xAxis.setTextSize(6);

        // 设置轴线文字的颜色
        xAxis.setTextColor(0xff878F99);

        // 设置轴线的宽度
        xAxis.setAxisLineWidth(2f);


        YAxis leftAxis = chart.getAxisLeft();

        leftAxis.setLabelCount(5, false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        // 设置轴线的颜色
        leftAxis.setAxisLineColor(0xff878F99);

        leftAxis.setTextColor(0xff878F99);

        leftAxis.setTextSize(6);

        // 设置网格线的样式为虚线
        leftAxis.setGridDashedLine(new DashPathEffect(new float[]{5f, 5f}, 0f));

        // 设置是否绘制轴线
        leftAxis.setDrawAxisLine(true);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);


        // set data


        // do not forget to refresh the chart
        // holder.chart.invalidate();
        chart.animateX(750);

        chart.getLegend().setEnabled(false); // 隐藏底部图例
        chart.getDescription().setText("时间");
        chart.getDescription().setTextColor(0xff7c8589);
        chart.getDescription().setTextSize(8);
        chart.getDescription().setEnabled(true);

    }

    private LineData generateDataLine(int cnt) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values1.add(new Entry(i, (int) (Math.random() * 65) + 40));
        }

        LineDataSet d1 = new LineDataSet(values1, "New DataSet " + cnt + ", (1)");
        d1.setDrawValues(false);
        d1.setDrawIcons(false);
        d1.setLineWidth(0.5f);
        d1.setColor(0xffF5555C);
        d1.setDrawCircles(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<Entry> values2 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values2.add(new Entry(i, values1.get(i).getY() - 30));
        }

        LineDataSet d2 = new LineDataSet(values2, "New DataSet " + cnt + ", (2)");
        d2.setLineWidth(0.5f);
        d2.setDrawValues(false);
        d2.setColor(0xffE68C5C);
        d2.setDrawCircles(false);
        d2.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);

        return new LineData(sets);
    }

    private LineData generateDataLine3(int cnt) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values1.add(new Entry(i, (int) (Math.random() * 65) + 40));
        }

        LineDataSet d1 = new LineDataSet(values1, "New DataSet " + cnt + ", (1)");
        d1.setDrawValues(false);
        d1.setDrawIcons(false);
        d1.setLineWidth(0.5f);
        d1.setColor(0xffE30708);
        d1.setDrawCircles(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<Entry> values2 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values2.add(new Entry(i, values1.get(i).getY() - 30));
        }

        LineDataSet d2 = new LineDataSet(values2, "New DataSet " + cnt + ", (2)");
        d2.setLineWidth(0.5f);
        d2.setDrawValues(false);
        d2.setColor(0xff0000F0);
        d2.setDrawCircles(false);
        d2.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<Entry> values3 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values3.add(new Entry(i, values1.get(i).getY() - 15));
        }

        LineDataSet d3 = new LineDataSet(values3, "New DataSet " + cnt + ", (2)");
        d3.setLineWidth(0.5f);
        d3.setDrawValues(false);
        d3.setColor(0xff101113);
        d3.setDrawCircles(false);
        d3.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);
        sets.add(d3);

        return new LineData(sets);
    }

    private LineData generateDataLine2(int cnt) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values1.add(new Entry(i, (int) (Math.random() * 65) + 40));
        }

        LineDataSet d1 = new LineDataSet(values1, "New DataSet " + cnt + ", (1)");
        d1.setDrawValues(false);
        d1.setDrawIcons(false);
        d1.setLineWidth(0.5f);
        d1.setColor(0xff5BC6EE);
        d1.setDrawCircles(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);

        return new LineData(sets);
    }


    private void setTempData() {


        ArrayList<Entry> values1 = new ArrayList<>();


        LineDataSet d1 = new LineDataSet(values1, "");
        d1.setDrawValues(false);
        d1.setDrawIcons(false);
        d1.setLineWidth(0.5f);
        d1.setColor(0xff5BC6EE);
        d1.setDrawCircles(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);

        LineData lineData = new LineData(sets);
        chartTemper.setData(lineData);


    }

    private LineData generateDataLine4(int cnt) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values1.add(new Entry(i, (int) (Math.random() * 65) + 40));
        }

        LineDataSet d1 = new LineDataSet(values1, "New DataSet " + cnt + ", (1)");
        d1.setDrawValues(false);
        d1.setDrawIcons(false);
        d1.setLineWidth(0.5f);
        d1.setColor(0xff76508B);
        d1.setDrawCircles(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置为平滑曲线模


        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);

        return new LineData(sets);
    }

    @Override
    public void onSubscriberDataChanged(Object notificationName, Object content) {
        if (EventNames.UPDATE_DATA == notificationName) {
            if (content != null) {
                UpdateDataModel updateDataModel = (UpdateDataModel) content;
                if ("spo2".equals(updateDataModel.type)) {
                    tvBlood.setText("血氧饱和度：" + updateDataModel.data + "");
                    messageData.o2 = updateDataModel.data;
                } else if ("temperature".equals(updateDataModel.type)) {
                    tvBlood.setText("体温：" + updateDataModel.data + "");
                }
                if(isStart){

                    models.add(updateDataModel);
                }

                reflushTemperData(chartTemper, updateDataModel);

            }
        }
    }

    private void reflushTemperData(LineChart chart, UpdateDataModel dataModel) {
        LineData data = chart.getData();
        if (data != null) {

            ILineDataSet set = data.getDataSetByIndex(0);

            if (dataModel.data != null || !dataModel.data.equals("")) {

                data.addEntry(new Entry(set.getEntryCount(), Float.valueOf(dataModel.data)), 0);

            } else {
                data.addEntry(new Entry(set.getEntryCount(), Float.valueOf(0)), 0);

            }

            data.notifyDataChanged();

            // let the chart know it's data has changed
            chart.notifyDataSetChanged();

            // limit the number of visible entries
            chart.setVisibleXRangeMaximum(120);
            // chart.setVisibleYRange(30, AxisDependency.LEFT);

            // move to the latest entry
            chart.moveViewToX(data.getEntryCount());

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getInstance().subscribe(EventNames.UPDATE_DATA, this);
    }

    @Override
    protected void onStop() {
        super.onStop();

        String cacheStr = (String)SpUtils.get(Cache_Key,"");

        ArrayList<MessageData> messageDataList = new ArrayList<>();

        Gson gson = new Gson();

        if(cacheStr != null && !"".equals(cacheStr)){


            ArrayList<MessageData> md = gson.fromJson(cacheStr, new TypeToken<List<MessageData>>() {
            }.getType());

            messageDataList.addAll(md);
        }
        messageDataList.add(0,messageData);

        String json = gson.toJson(messageDataList);


        SpUtils.put(Cache_Key, json);



    }

    @Override
    protected void onDestroy() {

        handler.removeCallbacks(updateTimeRunnable);


        EventBus.getInstance().unSubscribe(EventNames.UPDATE_DATA, this);

        super.onDestroy();

    }

    private String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        second = l.intValue();
        if (second > 60) {
            minute = second / 60; // 取整
            second = second % 60; // 取余
        }
        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }

        String minutemsg = "";
        String secondmsg = "";
        if (minute < 10) {
            minutemsg = "0" + minute;
        } else {
            minutemsg = minute + "";
        }

        if (second < 10) {
            secondmsg = "0" + second;
        } else {
            secondmsg = "" + second;
        }

        String strtime = minutemsg + ":" + secondmsg;
        return strtime;
    }


}
